/*
 * Copyright 2020 lcnap
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pers.lcnap.simplerpc.rpc;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.lcnap.simplerpc.rpc.handler.ServiceCallChannelHandler;
import pers.lcnap.simplerpc.rpc.handler.codec.ByteToRpcRequestDecoder;
import pers.lcnap.simplerpc.rpc.handler.codec.RpcResponseToByteEncoder;

/**
 * Netty Server 端启动,监听连接。加载相关服务实现类。
 */
public class NettyServer {

    final Logger logger = LoggerFactory.getLogger(NettyServer.class);

    private final EventLoopGroup bossGroup;

    private final EventLoopGroup workerGroup;

    private final ServerBootstrap serverBootstrap;

    private ChannelFuture closeFuture;

    private String host = "127.0.0.1";

    private int port = 8080;

    public NettyServer(String host, int port) {
        this();
        this.host = host;
        this.port = port;
    }

    public NettyServer(int port) {
        this();
        this.port = port;
    }

    public NettyServer() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        serverBootstrap = new ServerBootstrap();

        initServer();
    }


    private void initServer() {
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new ByteToRpcRequestDecoder())
                                .addLast(new RpcResponseToByteEncoder())
                                .addLast(new ServiceCallChannelHandler());

                    }
                });
    }


    public void run() {
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(host,port).sync();
            closeFuture = channelFuture.channel().closeFuture();
            logger.info("rpc server is listening on {}",port);
        } catch (InterruptedException e) {
            e.printStackTrace();
            shutdownGroup();
        }
    }

    public void shutdown() {
        closeFuture.channel().close();
        shutdownGroup();
        logger.info("rpc server is shutdown");
    }

    private void shutdownGroup() {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
